<template>
  <div class="page-modal">
    <el-dialog
      :title="title"
      v-model="DialogVisible"
      width="30%"
      center
      destroy-on-close
    >
      <zh-form v-bind="modelConfig" v-model="formData"></zh-form>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="DialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch, PropType } from 'vue'
import ZhForm from '@/base-ui/form'
import { useStore } from '@/store'

export default defineComponent({
  components: {
    ZhForm
  },
  props: {
    modelConfig: {
      type: Object,
      required: true
    },
    defaultInfo: {
      type: Object,
      default: () => ({})
    },
    title: {
      type: String,
      default: '操作'
    },
    pageName: {
      type: String,
      required: true
    },
    otherInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  setup(props) {
    const DialogVisible = ref(false)
    const formData = ref<any>({})
    const store = useStore()
    watch(
      () => props.defaultInfo,
      (newValue) => {
        for (const item of props.modelConfig.formItems) {
          formData.value[`${item.field}`] = newValue[`${item.field}`]
        }
      },
      { deep: true }
    )
    const handleConfirm = () => {
      DialogVisible.value = false
      if (Object.keys(props.defaultInfo).length) {
        store.dispatch('systems/editPageDataAction', {
          pageName: props.pageName,
          editData: { ...formData.value, ...props.otherInfo },
          id: props.defaultInfo.id
        })
      } else {
        store.dispatch('systems/createPageDataAction', {
          pageName: props.pageName,
          newData: { ...formData.value, ...props.otherInfo }
        })
      }
    }
    return {
      DialogVisible,
      formData,
      handleConfirm
    }
  }
})
</script>

<style scoped></style>
